package com.example.springboot_demo.demos.web.websocket_work.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.Session;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class OnlineUserService {
    private static final String ONLINE_USERS_KEY = "chat:online_users";
    private static final String USERS_SESSION_KEY = "chat:sessions";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 用户上线
    public void userLogin(String userId) {
        redisTemplate.opsForSet().add(ONLINE_USERS_KEY,userId);

        //若用户一直处于上线状态，存储一天后失效
        redisTemplate.expire(ONLINE_USERS_KEY,1,TimeUnit.DAYS);
    }

    // 用户下线
    public void userLogout(String userId) {
        redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, userId);
    }

    // 获取在线用户列表
    public Set<String> getOnlineUsers() {
        return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
    }

    //存储session会话信息
    public void storeSession(String userId, Session session) {
        redisTemplate.opsForHash().put(USERS_SESSION_KEY, userId,session.getId());
    }

    //获取session的会话信息
    public String findSessionById(String userId){
        String sessionId  = (String) redisTemplate.opsForHash().get(USERS_SESSION_KEY, userId);
        return sessionId;
    }

    //获取session的会话信息
    public void removeSession(String userId){
        redisTemplate.opsForHash().delete(USERS_SESSION_KEY,userId);
    }
}
